package com.acme.chat.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.acme.chat.client.ChatClient;
import com.acme.chat.message.ChatMessage;
import com.acme.chat.message.Message;

/**
 * Class represents remote ChatClient for the Server.
 */
public class TCPClient implements ChatClient, Runnable {
    private static final String ERROR_CLOSING_SOCKET = "Error closing socket!";
    private static final String ERROR_CLIENT_DISCONNECTS = "Client disconnects!";
    private static final String ERROR_UNKNOWN_CLIENT = "Unknown type of client!";
    private static final String ERROR_GET_STREAMS = "Can't get input and output streams!";

    private Server server;
    private Socket socket;
    private ObjectInputStream sInput;
    private ObjectOutputStream sOutput;
    private String room;
    private String name;

    private volatile boolean keepGoing = true;

    private static Logger tcpClientLogger = Logger.getLogger(TCPClient.class.getName());

    /**
     * Creates TCPClient instance for new connected client.
     *
     * @param socket
     * @param server
     */
    public TCPClient(Socket socket, Server server) {
        this.socket = socket;
        this.server = server;

        try {
            sOutput = new ObjectOutputStream(socket.getOutputStream());
            sInput = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            tcpClientLogger.info(ERROR_GET_STREAMS);
            tcpClientLogger.info(e.getMessage());
            close();
            return;
        }

        try {
            // on each connection user send here name and room
            name = (String) sInput.readObject();
            room = (String) sInput.readObject();
        } catch (IOException e) {
            tcpClientLogger.info(e.getMessage());
            close();
            return;
        } catch (ClassNotFoundException e) {
            tcpClientLogger.info(ERROR_UNKNOWN_CLIENT);
            tcpClientLogger.info(e.getMessage());
            close();
            return;

        }

        server.addClient(this);
    }

    @Override
    public String getRoom() {
        return room;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public boolean sendMessage(Message message) {
        try {
            sOutput.writeObject(message);
            return true;
        } catch (IOException e) {
            tcpClientLogger.info(e.getMessage());
            close();
            return false;
        }
    }

    @Override
    public void run() {
        Message message;
        while (keepGoing) {
            try {
                message = (ChatMessage) sInput.readObject();
                server.processMessage(message, this);
            } catch (IOException e) {
                tcpClientLogger.info(ERROR_CLIENT_DISCONNECTS);
                tcpClientLogger.info(e.getMessage());
                server.removeClient(this);
                keepGoing = false;
            } catch (ClassNotFoundException e) {
                tcpClientLogger.info(ERROR_UNKNOWN_CLIENT);
                tcpClientLogger.info(e.getMessage());
                server.removeClient(this);
                keepGoing = false;
            }
        }

        close();
    }

    /**
     * Creates new Thread and start TCPClient thread.
     */
    public void start() {
        (new Thread(this)).start();
    }

    @Override
    public boolean changeRoom(String room) {
        if (!this.room.equals(room)) {
            this.room = room;
            return true;
        }
        return false;
    }

    private void close() {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (Exception e) {
        	tcpClientLogger.info(ERROR_CLOSING_SOCKET);
        	tcpClientLogger.info(e.getMessage());
        }
    }

    @Override
    public void disconnect() {
        keepGoing = false;
        close();
    }

    @Override
    public int hashCode() {
        return this.name.hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof ChatClient)) {
            return false;
        }
        return this.name.equals(((ChatClient) o).getName());
    }

    @Override
    public String toString() {
        return "TCPClient: [name=" + name + "] [room=" + room + "] [socket=" + socket + "]";
    }
}
